package com.bawei.demoa.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bawei.demoa.R;
import com.bawei.demoa.adapter.MyAdapter;
import com.bawei.demoa.bean.NewsInfo;
import com.bawei.demoa.view.XListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/6/1 0001.
 */
public class ZiXunFragment extends Fragment implements XListView.IXListViewListener {

    private XListView lv;
    private String path = "http://www.oschina.net/action/api/news_list?catalog=1&pageSize=10&pageIndex=";
    int pageIndex = 1;
    Handler handler=new Handler();
    private ArrayList<NewsInfo> listAll=new ArrayList<>();
    private MyAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.zixun_frag, null);

        //找控件
        lv = (XListView) view.findViewById(R.id.lv);

        lv.setPullRefreshEnable(true);
        lv.setPullLoadEnable(true);

        lv.setXListViewListener(this);

        getData(1);

        return view;
    }

    /*
     *下拉刷新
     */
    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                listAll.clear();
                getData(1);
                onLoad();
            }
        },2000);
    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pageIndex++;
                getData(pageIndex);
                onLoad();
            }
        },2000);
    }

    private void onLoad() {
        lv.stopRefresh();
        lv.stopLoadMore();
        //获取系统当前时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd  HH:mm");
        String nowTime = format.format(new Date());
        lv.setRefreshTime(nowTime);
    }

    /**
     * 定义请求网络的方法
     */
    public void getData(final int index) {

                HttpUtils utils = new HttpUtils();
                utils.send(HttpRequest.HttpMethod.GET, path + index, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        try {
                            String str = responseInfo.result;
                            InputStream inputStream = new ByteArrayInputStream(str.getBytes("utf-8"));
                            List<NewsInfo> list = null;
                            NewsInfo news = null;
                            // 创建一个xml解析的工厂
                            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                            // 获得xml解析类的引用
                            XmlPullParser parser = factory.newPullParser();
                            parser.setInput(inputStream, "utf-8");
                            // 获得事件的类型
                            int eventType = parser.getEventType();
                            while (eventType != XmlPullParser.END_DOCUMENT) {
                                switch (eventType) {
                                    case XmlPullParser.START_DOCUMENT:
                                        list = new ArrayList<NewsInfo>();
                                        break;
                                    case XmlPullParser.START_TAG:
                                        if ("news".equals(parser.getName())) {
                                            news = new NewsInfo();
                                        } else if ("id".equals(parser.getName())) {
                                            String id = parser.nextText();// 获取该节点的内容
                                            news.setId(Integer.parseInt(id));
                                        } else if ("title".equals(parser.getName())) {
                                            String title = parser.nextText();
                                            news.setTitle(title);
                                        }else if ("body".equals(parser.getName())) {
                                            String body = parser.nextText();
                                            news.setBody(body);
                                        }else if ("commentCount".equals(parser.getName())) {
                                            String commentCount = parser.nextText();
                                            news.setCommentCount(commentCount);
                                        }else if ("pubDate".equals(parser.getName())) {
                                            String pubDate = parser.nextText();
                                            news.setPubDate(pubDate);
                                        }else if ("author".equals(parser.getName())) {
                                            String author = parser.nextText();
                                            news.setAuthor(author);
                                        }
                                        break;
                                    case XmlPullParser.END_TAG:
                                        if ("news".equals(parser.getName())) {
                                            list.add(news);
                                            news = null;
                                        }
                                        break;
                                }
                                eventType = parser.next();
                            }
                            listAll.addAll(list);
                            if (adapter==null){
                                //设置适配器
                                lv.setAdapter(adapter=new MyAdapter(getActivity(),listAll));
                            }else{
                                adapter.notifyDataSetChanged();
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                    }
                });
    }
}
